package com.xja.web.domain.commons;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.IOException;

public class HttpClienUtil {

    public static JSONObject doGet(String url) throws IOException {
        JSONObject jsonObject=null;
        //指定请求方式
        HttpGet get= new HttpGet(url);
        //获取httpClient准备发送请求
        HttpClient httpClient = new DefaultHttpClient();

            //执行发送请求并获得响应结果
            HttpResponse httpResponse = httpClient.execute(get);
            //如果请求发送出去为正常（200）
            if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                //将请求中的响应结果转换为字符串并加上字符集设置
                String ss  = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
                //转换成json 存值为hashmap
                 jsonObject = new JSONObject(ss);
            }

        return jsonObject;
    }
    public static JSONObject doPost(String url,String data) throws IOException {
        JSONObject jsonObject=null;
        //指定请求方式
        HttpPost psot= new HttpPost(url);
        //获取httpClient准备发送请求
        HttpClient httpClient = new DefaultHttpClient();
        psot.setEntity(new StringEntity(data,"utf-8"));
        //执行发送请求并获得响应结果
        HttpResponse httpResponse = httpClient.execute(psot);
        //如果请求发送出去为正常（200）
        if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
            //将请求中的响应结果转换为字符串并加上字符集设置
            String ss  = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
            //转换成json 存值为hashmap
            jsonObject = new JSONObject(ss);
        }

        return jsonObject;
    }


}
